import hdyConfig from "@/config/index";
import _ from 'lodash'
import {
	mapMutations
} from 'vuex';
const goLogin = () => {
	uni.$u.toast("登录已过期");
	// store.dispatch("setToken", '');
	uni.clearStorage();
	// uni.removeStorageSync('user');
	// uni.removeStorageSync('token');
	// uni.removeStorageSync('userInfo');
	// uni.removeStorageSync('code');
	// uni.removeStorageSync('vipInfo');
	setTimeout(() => {
		uni.$u.route({
			url: '/views/login/index',
			type: "reLaunch",
		});
	}, 500);
};
// let changeLoading = mapMutations('loading', ['SET_LOADING']).SET_LOADING
const defaultConfig = {
	baseURL: hdyConfig.baseURL,
	method: "POST",
	dataType: "json",
	showLoading: true,
	loadingText: "请求中...",
	loadingTime: 3000,
	originalData: true,
	loadingMask: true,
	header: {
		"content-type": 'application/x-www-form-urlencoded',
	},
};

module.exports = (vm) => {
	// 初始化请求配置
	uni.$u.http.setConfig((config) => {
		/* config 为默认全局配置*/
		config = defaultConfig
		return config
	})

	// 请求拦截
	uni.$u.http.interceptors.request.use(async (config) => { // 可使用async await 做异步操作
		let type = null
		// uni.getNetworkType({
		// 	success: (res) => {
		// 		type = res.networkType
		// 	}
		// })
		if (type !== 'none') {
			config.header.token = uni.getStorageSync('token') //'8b29492b-2050-428f-823b-e23f4125799a' ||
			//非开放请求（需要TOKEN）,却没有TOKEN的直接处理为身份过期, 未通过拦截, 直接跳到转到登陆
			let isNoToken = config.url.includes('login');

			if (config?.data?.loading || config?.params?.loading) {
				uni.showLoading({
					title: "加载中"
				});
			}
			
			if (
				isNoToken == false &&
				config.header.token == ""
			) {
				goLogin();
				return false;
			}

			if (isNoToken == true) {
				config.header.token = ''
			}
		} else {
			uni.showToast({
				title: '无网络连接，请检查网络',
				icon: 'none'
			})
		}
		return config
	}, config => {
		return Promise.reject(config)
	})

	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => {
		// console.log(response)
		/* 对响应成功做点什么 可使用async await 做异步操作*/
		const {
			statusCode,
			data
		} = response;
		uni.hideLoading()
		switch (statusCode) {
			case 200:
				return response?.data;
				break;
			case 400:
				uni.$u.toast(data.msg)
				break;
			case 401:
				goLogin(vm);
				return false;
				break;
			default:
				uni.$u.toast("未知状态码，出了点问题！");
				return false;
				break;
		}

		return Promise.reject(data)
	}, (response) => {
		// 对响应错误做点什么 （statusCode !== 200）
		// console.log('response', response)
		uni.hideLoading()
		return Promise.reject(response)
	})
}